﻿using OpenGL;

namespace SDL2_OpenGL_ImGui;

public class Texture
{ 
    public uint Id { get; }
    public Texture(IntPtr pixelData, int width, int height, PixelFormat format = PixelFormat.Rgba, InternalFormat internalFormat = InternalFormat.Rgba)
    {
        Gl.GetInteger(GetPName.TextureBinding2d, out uint lastTex);
        Id = Gl.GenTexture();
        Gl.PixelStore(PixelStoreParameter.PackAlignment, 1);
        Gl.BindTexture(TextureTarget.Texture2d, Id);
        Gl.TexImage2D(TextureTarget.Texture2d, 0, internalFormat, width, height, 0, format,PixelType.UnsignedByte, pixelData);
        Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureWrapS, TextureWrapMode.Repeat);
        Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureWrapT, TextureWrapMode.Repeat);
        Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureMagFilter, TextureMagFilter.Linear);
        Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureMinFilter, TextureMinFilter.Linear);
        Gl.BindTexture(TextureTarget.Texture2d, lastTex);
    }
 
    public Texture(byte[] pixelData, int width, int height, PixelFormat format = PixelFormat.Rgba, InternalFormat internalFormat = InternalFormat.Rgba)
    {
        Gl.GetInteger(GetPName.TextureBinding2d, out uint lastTex);
        Id = Gl.GenTexture();
        Gl.PixelStore(PixelStoreParameter.PackAlignment, 1);
        Gl.BindTexture(TextureTarget.Texture2d, Id);
        Gl.TexImage2D(TextureTarget.Texture2d, 0, internalFormat, width, height, 0, format,PixelType.UnsignedByte, pixelData);
        Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureWrapS, TextureWrapMode.Repeat);
        Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureWrapT, TextureWrapMode.Repeat);
        Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureMagFilter, TextureMagFilter.Linear);
        Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureMinFilter, TextureMinFilter.Linear);
        Gl.BindTexture(TextureTarget.Texture2d, 0);
        Gl.BindTexture(TextureTarget.Texture2d, lastTex);
    }

    ~Texture()
    {
        Gl.DeleteTextures(Id);
    }

    public void Bind()
    {
        Gl.BindTexture(TextureTarget.Texture2d, Id);
    }
}